/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ipccenter.security;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.persistence.PersistenceException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import ru.ipccenter.beans.HumanBeanLocal;
import ru.ipccenter.beans.RoleBeanLocal;
import ru.ipccenter.entities.Human;
import ru.ipccenter.entities.Role;

/**
 *
 * @author sm-ni_000
 */
public class MyRealm extends AuthorizingRealm{
    private final static Logger log = Logger.getLogger(MyRealm.class.getName());
    private final static String REALM_NAME = "myRealm";

    @EJB
    private HumanBeanLocal userDAO;
    @EJB
    private RoleBeanLocal roleDAO;
    
    public MyRealm() {
    }

    protected SimpleAuthenticationInfo getAuthenticationInfo(String login, String password) throws AuthenticationException {
        UsernamePasswordToken token = new UsernamePasswordToken(login, password);
        token.setRememberMe(true);
        
        Human user = null; 
        try {
            user = userDAO.findByLogin(login);
        } catch (PersistenceException e) {
            log.log(Level.SEVERE, null, e);
            return null;
        }
        
        if (user != null) {
            return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), user.getLogin());
        } else {
            return null;
        }
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Long userId = (Long) principals.fromRealm(REALM_NAME).iterator().next();
        Human user = userDAO.find(userId);
        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            Role role;
            role = roleDAO.findByHuman(user);
            info.addRole(role.getName());
            return info;
        } else {
            return null;
        }
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) throws AuthenticationException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
